//
//  GTLibCoreUtils.swift
//  lib_core
//
//  Created by Shper on 2023/9/7.
//

import Foundation

class GTLibCoreUtils {
    
    /**
     * 字典转成 Json
     */
    static func convertDictionaryToString(_ dict: [String : Any]) -> String {
        var result: String = ""
        do {
            if #available(iOS 13.0, *) {
                let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [.sortedKeys, .withoutEscapingSlashes])
                if let jsonStr = String(data: jsonData, encoding: String.Encoding.utf8) {
                    result = jsonStr
                }
            } else {
                var components: [String] = []
                for key in dict.keys.sorted(by: <) {
                    let value = dict[key]!
                    components.append(queryComponents(fromKey: key, value: value))
                }
                result = "{\(components.joined(separator: ","))}"
            }
        } catch {
            result = ""
        }
        return result
    }

    private static func queryComponents(fromKey key: String?, value: Any) -> String {
        var keyFix = ""
        if let key = key { keyFix = "\"\(key)\":" }
        
        var components: String = ""
        switch value {
        case let dictionary as [String: Any]:
            var items: [String] = []
            for (nestedKey, value) in dictionary {
                items.append("\(queryComponents(fromKey: nestedKey, value: value))")
            }
            components = "\(keyFix){\(items.joined(separator: ","))}"
        case let array as [Any]:
            var items: [String] = []
            for (_, value) in array.enumerated() {
                items.append("\(queryComponents(fromKey: nil, value: value))")
            }
            components = "\(keyFix)[\(items.joined(separator: ","))]"
        case let string as String:
            components = "\(keyFix)\"\(string.replacingOccurrences(of: "\\", with: ""))\""
        default:
            components = "\(keyFix)\(value)"
        }
        return components
    }
    
}
